package com.bird.common.utils.function;

import cn.hutool.core.util.ReflectUtil;
import com.bird.common.utils.StringUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class FunctionExecutor {


	Pattern[] patterns;

	public FunctionExecutor() {
		String[] functionPattern = getFunctionPattern();
		patterns = new Pattern[functionPattern.length];
		for (int i = 0; i < patterns.length; i++) {
			patterns[i] = Pattern.compile(functionPattern[i]);
		}
	}

	/**
	 * 函数名称
	 *
	 * @return
	 */
	abstract String[] getFunctionPattern();


	/**
	 * 处理函数表达式
	 *
	 * @param content
	 * @return
	 */
	public String handleFunction(String content) {
		for (Pattern pattern : patterns) {
			Matcher matcher = pattern.matcher(content);
			while (matcher.find()) {
				// 获取表达式
				String exp = matcher.group();
				String methodName = getMethodName(exp);
				String[] methodParam = getMethodParam(exp);
				Object objectValue;
				if (methodParam == null) {
					objectValue = ReflectUtil.invoke(this, methodName);
				} else {
					objectValue = ReflectUtil.invoke(this, methodName, methodParam);
				}
				String returnValue = String.valueOf(objectValue);
				content = content.replaceFirst(pattern.pattern(), returnValue);
			}
		}
		return content;
	}

	/**
	 * 获取方法名
	 *
	 * @return
	 */
	private String getMethodName(String exp) {
		int first = exp.indexOf(".") + 1;
		int end = exp.indexOf("(");
		return exp.substring(first, end);
	}

	/**
	 * 获取方法名
	 *
	 * @return
	 */
	private String[] getMethodParam(String exp) {
		int first = exp.indexOf("(") + 1;
		int end = exp.lastIndexOf(")");
		String params = exp.substring(first, end);
		if (StringUtil.isBlank(params)) {
			return null;
		}
		return params.split(",");
	}


	public static void main(String[] args) {
		String c = "我是${random.string(10)}, 今天${random.randomLong(1,5)}号 时间${date.now(yyyy-MM-dd)}, 天气气温是${random.randomDouble(17,40)}度, 我骑着编号为${random.uuid()}的车子去公园, 路程总共耗时${date.nowMillis()}毫秒, 也就是${date.nowSeconds()}秒";
		RandomFunctionExecutor r = new RandomFunctionExecutor();
		DateFunctionExecutor d = new DateFunctionExecutor();
		c = r.handleFunction(c);
		c = d.handleFunction(c);
		System.out.println(c);
		System.out.println(System.currentTimeMillis());
	}


}
